#include "workwindow.h"
#include "ui_workwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QDateTime>
Workwindow::Workwindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Workwindow)
{
    ui->setupUi(this);
    ui->stackedWidget->setCurrentIndex(0);
    socketNickModi = new QTcpSocket(this); //修改昵称的套接字初始化
    socketPasswdModi = new QTcpSocket(this); //修改密码套接字初始化
    socketCommitTemp = new QTcpSocket(this); //提交当日的账单信息到服务器数据库
    socketGetOnedInfo = new QTcpSocket(this); //提交账单完成后，获取当天的账单信息，并显示到预览页面
    socketGetSearInfo = new QTcpSocket(this); //获取选择好的某一天的账单信息，并显示到预览页面
    socketPriorInfo = new QTcpSocket(this); //前一天按钮的通信套接字
    socketNextInfo = new QTcpSocket(this); //后一天按钮的通信套接字
    ui->comboBoxAddType->addItem( "衣" );
    ui->comboBoxAddType->addItem( "食" );
    ui->comboBoxAddType->addItem( "住" );
    ui->comboBoxAddType->addItem( "行" );
    ui->comboBoxAddType->addItem( "其它" );
    ui->comboBoxAddType->addItem( "请选择类别" );
    ui->comboBoxAddType->setCurrentText( "请选择类别" );
    int i = 0;
    ui->comboBoxYear->addItem( "请选择年份" );
    for( i = 0 ; i < 30 ; i++ )
    {
        ui->comboBoxYear->addItem( QString::number( 2020 + i ));
    }
    ui->comboBoxMonth->addItem( "请选择月份" );
    for( i = 0 ; i < 12; i++ )
    {
        if( i < 9 )
        {
            ui->comboBoxMonth->addItem( QString( "0%1").arg(i+1));
            continue;
        }
        else
        {
            ui->comboBoxMonth->addItem( QString::number(i+1));
        }

    }
    ui->comBoxDay->addItem( "请选择日期" );
    days.push_back("31");
    days.push_back("28");
    days.push_back("31");
    days.push_back("30");
    days.push_back("31");
    days.push_back("30");
    days.push_back("31");
    days.push_back("31");
    days.push_back("30");
    days.push_back("31");
    days.push_back("30");
    days.push_back("31");
    connectTempDb( "temp" );
    /*
     * 无法实现的异常功能，此处为主页关闭的时候想登录窗口发送一个信号
    connect( this , Workwindow::destroyed ,
             [=]()
             {
                emit on_destroyed_Signal();
             }
           );
    */
    connect( socketNickModi , QTcpSocket::connected ,
             [=]()
             {
                if( ui->lineEditNickname->text().isEmpty() )
                {
                   QMessageBox::warning( this , "警告" , "请输入昵称" );
                   socketNickModi->disconnectFromHost();
                   return;
                }
                QString str = "6" + this->username + "#" + ui->lineEditNickname->text();
                socketNickModi->write( str.toUtf8() );
             }
           );
    connect( socketNickModi , QTcpSocket::readyRead ,
             [=]()
             {
                QByteArray bytes = socketNickModi->readAll();
                QString str = QString(bytes);
                if( "61000" == str )
                {
                    QMessageBox::information( this , "成功" , "昵称更改成功" );
                }
                if( "61001" == str )
                {
                    QMessageBox::information( this , "失败" , "昵称修改失败" );
                }
                socketNickModi->disconnectFromHost();
             }
           );
    connect( socketPasswdModi , QTcpSocket::connected ,
             [=]()
             {
                if( true == ui->lineEditOldpasswd->text().isEmpty() ||
                    true == ui->lineEditNewpasswd->text().isEmpty() ||
                    true == ui->lineEditNewpasswdsure->text().isEmpty()
                  )
                {
                     QMessageBox::warning( this , "错误" , "请输入正确的密码信息" );
                     socketPasswdModi->disconnectFromHost();
                     return;
                }
                if( ui->lineEditNewpasswd->text() != ui->lineEditNewpasswdsure->text() )
                {
                    QMessageBox::warning( this , "错误" , "请保持两次输入的新密码一致" );
                    socketPasswdModi->disconnectFromHost();
                    return;
                }
                QString str = "0" + username + "#" + ui->lineEditOldpasswd->text();
                socketPasswdModi->write( str.toUtf8() );
             }
           );
    connect( socketPasswdModi , QTcpSocket::readyRead ,
             [=]()
             {
                QByteArray bytes = socketPasswdModi->readAll();
                QString str = QString(bytes);
                if( "51000" == str )
                {
                    QMessageBox::information( this , "成功" , "修改密码成功" );
                    socketPasswdModi->disconnectFromHost();
                }
                if( "51001" == str )
                {
                    QMessageBox::information( this , "失败" , "修改密码失败" );
                    socketPasswdModi->disconnectFromHost();
                }
                if( "10000" == str )
                {
                    str = "5" + username + "#" + ui->lineEditNewpasswd->text();
                    socketPasswdModi->write( str.toUtf8() );
                }
                if( "10001" == str )
                {
                    QMessageBox::warning( this , "失败" , "旧密码错误" );
                    socketPasswdModi->disconnectFromHost();
                }
             }

           );
    connect( socketCommitTemp , QTcpSocket::connected ,
             [=]()
             {
                QSqlQuery query;
                bool flag = query.exec( "select * from temp");
                if( false == flag )
                {
                    QMessageBox::information( this , "失败" , "提交失败" );
                    return;
                }
                QString buff;
                buff = "3" + this->username;
                while( query.next() )
                {

                    buff += "#" ;
                    buff += "'" + query.value(0).toString() + "'" + "," ;
                    buff +=  query.value(1).toString() + "," ;
                    buff += "'" + query.value(2).toString() + "'";

                }
                socketCommitTemp->write( buff.toUtf8() );
             }
           );
    connect( socketCommitTemp , QTcpSocket::readyRead ,
             [=]()
            {
                QByteArray bytes = socketCommitTemp->readAll();
                QString str = QString( bytes );
                if( "31000" == str )
                {
                    QMessageBox::information( this , "成功" , "提交成功" );
                    model->clear();
                    //删除本地暂存中所有的记录
                    //获取选中的模型
                    ui->tableView->selectAll();
                    QItemSelectionModel *sModel = ui->tableView->selectionModel();
                    //取出模型中的索引
                    QModelIndexList list = sModel->selectedRows();
                    //删除所有选中的行
                    for(int i = 0; i < list.size(); i++)
                    {
                        model->removeRow( list.at(i).row() );
                    }
                    //删除结束
                    socketCommitTemp->disconnectFromHost();
                    socketGetOnedInfo->connectToHost( QHostAddress(IP) , 8888 );
                    QDateTime dateTime(QDateTime::currentDateTime());
                    QString year = dateTime.toString("yyyy");
                    QString month = dateTime.toString( "MM" );
                    QString days = dateTime.toString( "dd" );
                    ui->comboBoxYear->setCurrentText( year );
                    ui->comboBoxMonth->setCurrentText( month );
                    ui->comBoxDay->setCurrentText(days);

                }
                if( "31001" == str )
                {
                    QMessageBox::information( this , "失败" , "提交失败" );

                }
                socketCommitTemp->disconnectFromHost();
            }

           );
    connect( socketGetOnedInfo , QTcpSocket::connected ,
             [=]()
             {
                QString buf = "2";
                buf += this->username;
                buf += "#";
                QDateTime dateTime(QDateTime::currentDateTime());
                QString qStr = dateTime.toString("yyyyMMdd");
                buf += qStr;
                socketGetOnedInfo->write( buf.toUtf8() );
            }
           );
    connect( socketGetOnedInfo , QTcpSocket::readyRead ,
             [=]()
             {
                ui->textEdit->clear();
                QByteArray arr = socketGetOnedInfo->readAll();
                QString tempstr = QString(arr);
                if( "21001" == tempstr.mid(0,5))
                {
                    QMessageBox::warning(this,"提示","服务器错误");
                    ui->textEdit->setText("21001,服务器错误,当天的记录账目不存在");
                 }
                if( "21000" == tempstr.mid(0,5))
                {
                    QMessageBox::information(this,"提示" , "记得记录今天的花费哦");
                    ui->textEdit->setText(tempstr.mid(5));
                }
                socketGetOnedInfo->disconnectFromHost();
                return;
             }
           );
    connect( socketGetSearInfo , QTcpSocket::connected ,
             [=]()
            {
                QString buf = "2";
                buf += this->username;
                buf += "#";
                QString qStr = ui->comboBoxYear->currentText() + ui->comboBoxMonth->currentText() + ui->comBoxDay->currentText();
                buf += qStr;
                qDebug() << buf;
                socketGetSearInfo->write( buf.toUtf8() );
            });
    connect( socketGetSearInfo , QTcpSocket::readyRead ,
             [=]()
            {
                ui->textEdit->clear();
                QByteArray arr = socketGetSearInfo->readAll();
                QString tempstr = QString(arr);
                if( "21001" == tempstr.mid(0,5))
                {
                    QMessageBox::warning(this,"提示","服务器错误");
                    ui->textEdit->setText("21001,服务器错误,当天的记录账目不存在");
                }
                if( "21000" == tempstr.mid(0,5))
                {
                     QMessageBox::information(this,"提示" , "记得记录今天的花费哦");
                     ui->textEdit->setText(tempstr.mid(5));

                }
                socketGetSearInfo->disconnectFromHost();
                return;
            }
           );
    connect( socketPriorInfo , QTcpSocket::connected ,
            [=]()
            {
                if( ui->comboBoxYear->currentText() == "请选择年份" ||
                    ui->comboBoxMonth->currentText() == "请选择月份" ||
                    ui->comBoxDay->currentText() == "请选择日期"
                  )
                {
                    QString buf = "2";
                    buf += this->username;
                    buf += "#";
                    QDateTime dateTime(QDateTime::currentDateTime());
                    QString qStr = dateTime.toString("yyyyMMdd");
                    buf += qStr;
                    socketPriorInfo->write( buf.toUtf8() );
                    QString year = dateTime.toString("yyyy");
                    QString month = dateTime.toString( "MM" );
                    QString days = dateTime.toString( "dd" );
                    ui->comboBoxYear->setCurrentText( year );
                    ui->comboBoxMonth->setCurrentText( month );
                    ui->comBoxDay->setCurrentText(days);
                    return;
                }
                else
                {
                    QString year = ui->comboBoxYear->currentText();
                    QString month = ui->comboBoxMonth->currentText();
                    QString day = ui->comBoxDay->currentText();
                    int numyear = year.toInt();
                    int nummonth = month.toInt();
                    int numday = day.toInt();
                    numday--;
                    if(  numday <= 0 )
                    {
                        nummonth--;
                        if( nummonth <= 0 )
                        {
                            numyear--;
                            nummonth = 12;
                        }
                        numday = QString( days.at( nummonth - 1 ) ).toInt();
                        if( ( numyear % 400 == 0 || numyear % 4 == 0 && numyear % 100 != 0 ) && nummonth == 2  )
                        {
                            numday++;
                        }
                    }
                    QString stryear  = QString::number(numyear);
                    QString strmonth;
                    if( nummonth <= 9 )
                    {
                        strmonth = QString("0%1").arg(nummonth);
                    }
                    else
                    {
                        strmonth = QString::number(nummonth);
                    }
                    QString strday;
                    if( numday <= 9 )
                    {
                        strday = QString( "0%1" ).arg(numday);
                    }
                    else
                    {
                        strday = QString::number(numday);
                    }
                    ui->comboBoxYear->setCurrentText( stryear );
                    ui->comboBoxMonth->setCurrentText( strmonth );
                    ui->comBoxDay->setCurrentText( strday );
                    QString buf = "2";
                    buf += this->username;
                    buf += "#";
                    buf += stryear;
                    buf += strmonth;
                    buf += strday;
                    qDebug() << "prior" << buf;
                    socketPriorInfo->write( buf.toUtf8() );
                    return;
                }
                socketPriorInfo->disconnectFromHost();
            }

           );
    connect( socketPriorInfo , QTcpSocket::readyRead ,
             [=]()
            {
                ui->textEdit->clear();
                QByteArray arr = socketPriorInfo->readAll();
                QString tempstr = QString(arr);
                if( "21001" == tempstr.mid(0,5))
                {
                    QMessageBox::warning(this,"提示","服务器错误");
                    ui->textEdit->setText("21001,服务器错误,当天的记录账目不存在");
                }
                if( "21000" == tempstr.mid(0,5))
                {
                    QMessageBox::information(this,"提示" , "记得记录今天的花费哦");
                    ui->textEdit->setText(tempstr.mid(5));

                }
                socketPriorInfo->disconnectFromHost();
            }

           );
    connect( socketNextInfo , QTcpSocket::connected ,
             [=]()
            {
                if( ui->comboBoxYear->currentText() == "请选择年份" ||
                    ui->comboBoxMonth->currentText() == "请选择月份" ||
                    ui->comBoxDay->currentText() == "请选择日期"
                    )
                {
                    QString buf = "2";
                    buf += this->username;
                    buf += "#";
                    QDateTime dateTime(QDateTime::currentDateTime());
                    QString qStr = dateTime.toString("yyyyMMdd");
                    buf += qStr;
                    socketNextInfo->write( buf.toUtf8() );
                    QString year = dateTime.toString("yyyy");
                    QString month = dateTime.toString( "MM" );
                    QString days = dateTime.toString( "dd" );
                    ui->comboBoxYear->setCurrentText( year );
                    ui->comboBoxMonth->setCurrentText( month );
                    ui->comBoxDay->setCurrentText(days);
                    return;
                }
                else
                {
                    QString year = ui->comboBoxYear->currentText();
                    QString month = ui->comboBoxMonth->currentText();
                    QString day = ui->comBoxDay->currentText();
                    int numyear = year.toInt();
                    int nummonth = month.toInt();
                    int numday = day.toInt();
                    numday++;
                    int maxnumday = QString( days.at(nummonth-1)).toInt();
                    if( ( numyear % 400 == 0 || numyear % 4 == 0 && numyear % 100 != 0 ) && nummonth == 2  )
                    {
                        maxnumday++;
                    }
                    if(  numday > maxnumday  )
                    {
                        numday = 1;
                        nummonth++;
                        if( nummonth > 12 )
                        {
                            numyear++;
                            nummonth = 1;
                        }
                    }
                    QString stryear  = QString::number(numyear);
                    QString strmonth;
                    if( nummonth <= 9 )
                    {
                        strmonth = QString("0%1").arg(nummonth);
                    }
                    else
                    {
                        strmonth = QString::number(nummonth);
                    }
                    QString strday;
                    if( numday <= 9 )
                    {
                        strday = QString( "0%1" ).arg(numday);
                    }
                    else
                    {
                        strday = QString::number(numday);
                    }
                    ui->comboBoxYear->setCurrentText( stryear );
                    ui->comboBoxMonth->setCurrentText( strmonth );
                    ui->comBoxDay->setCurrentText( strday );
                    QString buf = "2";
                    buf += this->username;
                    buf += "#";
                    buf += stryear;
                    buf += strmonth;
                    buf += strday;
                    socketNextInfo->write( buf.toUtf8() );
                    return;
                }
                socketNextInfo->disconnectFromHost();
            }
           );
    connect( socketNextInfo , QTcpSocket::readyRead ,
             [=]()
             {
                ui->textEdit->clear();
                QByteArray arr = socketNextInfo->readAll();
                QString tempstr = QString(arr);
                if( "21001" == tempstr.mid(0,5))
                {
                    QMessageBox::warning(this,"提示","服务器错误");
                    ui->textEdit->setText("21001,服务器错误,当天的记录账目不存在");
                }
                if( "21000" == tempstr.mid(0,5))
                {
                     QMessageBox::information(this,"提示" , "记得记录今天的花费哦");
                    ui->textEdit->setText(tempstr.mid(5));

                }
                socketNextInfo->disconnectFromHost();
             }
           );
}

Workwindow::~Workwindow()
{
    delete ui;
}
//连接数据库的函数，用于暂存临时的账目信息
void Workwindow::connectTempDb(QString strname)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE" ) ;
    QSqlQuery query;
    QString str = QCoreApplication::applicationDirPath() + "/temp.db" ;
    qDebug() << str ;
    db.setDatabaseName( str );
    if( false == db.open() )
    {
        QMessageBox::warning( this , "失败" , db.lastError().text() ) ;
        qDebug() << "打开失败" ;
        return ;
    }

    bool flag = query.exec( "create table temp if not exists( item varchar primary key not null , price int not null , type var char not null );" );
    if( false == flag )
    {
       qDebug() << "创建或者打开数据库失败";
    }
    //设置模型
    this->model = new QSqlTableModel(this);
    this->model->setTable("temp");//制定使用哪个表

    //把model放在view
    ui->tableView->setModel(model);

    //显示model里的数据
    this->model->select();

    this->model->setHeaderData(0, Qt::Horizontal, "学号");

    //设置model的编辑模式，手动提交修改
    this->model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    //设置view中的数据库不允许修改
    //ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
void Workwindow::setUsername( QString str )
{
    this->username = str;
    this->setWindowTitle( "welcome" + this->username );
}
void Workwindow::setIp( QString str )
{
    this->IP = str;
}
//预览菜单选项被触发
void Workwindow::on_actionGlance_triggered()
{
    ui->stackedWidget->setCurrentIndex(0);
    ui->labelPageName->setText( "预 览" );
}
//添加账目菜单选项被触发
void Workwindow::on_actionAdd_triggered()
{
    ui->stackedWidget->setCurrentIndex(2);
    ui->labelPageName->setText( "添 加");

}
//修改用户信息菜单选项被触发
void Workwindow::on_actionUserInfoModi_triggered()
{
    ui->stackedWidget->setCurrentIndex(1);
    ui->labelPageName->setText( "修改" );
}
//修改昵称按钮
void Workwindow::on_pushButtonModinickname_clicked()
{
    if( true == ui->lineEditNickname->text().isEmpty() )
    {
        return;
    }
    socketNickModi->connectToHost( QHostAddress(this->IP) , 8888 );
}
//修改密码按钮
void Workwindow::on_pushButton_4_clicked()
{
    if( true == ui->lineEditOldpasswd->text().isEmpty() ||
        true == ui->lineEditNewpasswd->text().isEmpty() ||
        true == ui->lineEditNewpasswdsure->text().isEmpty()
      )
      {
           QMessageBox::warning( this , "错误" , "请输入正确的密码信息" );
           return;
      }
    if( ui->lineEditNewpasswd->text() != ui->lineEditNewpasswdsure->text() )
    {
           QMessageBox::warning( this , "错误" , "请保持两次输入的新密码一致" );
           return;
    }
    socketPasswdModi->connectToHost( QHostAddress(IP) , 8888 );
}
//添加记录按钮
void Workwindow::on_pushButtonAddAdd_clicked()
{
    if( ui->comboBoxAddType->currentText() == "请选择类别"
        || ui->lineEditConsumepri->text().isEmpty()
        || ui->lineEditCusumeItem->text().isEmpty())
    {
        QMessageBox::warning( this , "错误" , "请输入正确的消费记录" );
        return;
    }
    //添加空记录
    QSqlRecord record = model->record(); //获取空记录
    //QSqlField field;
    //获取行号
    int row = model->rowCount();
    model->insertRecord(row, record);
}
//取消
void Workwindow::on_pushButtonCancel_clicked()
{
    model->revertAll(); //取消所用动作
    model->submitAll(); //提交动作
}
//确认
void Workwindow::on_pushButton_3_clicked()
{
     model->submitAll(); //提交动作
}
//删除
void Workwindow::on_pushButtonDel_clicked()
{
    //获取选中的模型
    QItemSelectionModel *sModel =ui->tableView->selectionModel();
    //取出模型中的索引
    QModelIndexList list = sModel->selectedRows();
    //删除所有选中的行
    for(int i = 0; i < list.size(); i++)
    {
        model->removeRow( list.at(i).row() );
    }
}
//添加账目信息后将账目信息提交到服务器数据库存储
void Workwindow::on_pushButtonAddCommit_clicked()
{
    socketCommitTemp->connectToHost( QHostAddress(IP) , 8888);
}
//月份的当前选项发生变化时的动作
void Workwindow::on_comboBoxMonth_currentIndexChanged(const QString &arg1)
{
    if( "请选择年份" == ui->comboBoxYear->currentText() ||
        "请选择月份" == ui->comboBoxMonth->currentText()
      )
    {
        return;
    }
    int i;
    ui->comBoxDay->clear();
    ui->comBoxDay->addItem( "请选择日期" );
    int month = ui->comboBoxMonth->currentText().toInt();
    QString daynum = days.at(month-1);
    int lenth = daynum.toInt();
    int year = ui->comboBoxYear->currentText().toInt();
    if( ( year % 400 == 0 || year % 4 == 0 && year %100 != 0 ) && month == 2 )
    {
        lenth++;
    }
    for( i = 1 ; i <=lenth ; i++ )
    {
        if( i <= 9 )
        {
            ui->comBoxDay->addItem( QString("0%1").arg(i));
            continue;
        }
        ui->comBoxDay->addItem( QString::number(i) );
    }

}
//选择好指定日期后，点击查找按钮，立刻查找
void Workwindow::on_pushButton_5_clicked()
{
    socketGetSearInfo->connectToHost( QHostAddress(IP) , 8888);
}
//按下前一天按钮切换到之前的账单
void Workwindow::on_pushButton_clicked()
{
    socketPriorInfo->connectToHost( QHostAddress(IP) , 8888);
}
//按下后一天按钮切换到之后的账单
void Workwindow::on_pushButton_2_clicked()
{
    socketNextInfo->connectToHost( QHostAddress(IP) , 8888);
}
